// 多个线程执行抢票
#include <iostream>
#include <cstdio>
#include <unistd.h>
#include <pthread.h>
#include <string>

using namespace std;
#define Thread_NUM 5

class ThreadData
{
public:
    ThreadData(const string &name, pthread_mutex_t *pm)
        : t_name(name), pmtx(pm)
    {
    }

    string t_name;
    pthread_mutex_t *pmtx;
};

int ticket = 50;
void *getTicket(void *args)
{
    ThreadData *td = (ThreadData *)args;

    while (1)
    {
        pthread_mutex_lock(td->pmtx);
        // 临界区
        if (ticket > 0)//判断也是计算的一种
        {
            printf("%s get ticket, rest: %d\n", td->t_name.c_str(), ticket);
            ticket--;
            pthread_mutex_unlock(td->pmtx);
        }
        else
        {
            pthread_mutex_unlock(td->pmtx);
            break;
        }
        //做其它动作
        usleep(rand()%2000);
    }
    delete td;
    return nullptr;
}

int main()
{
    srand((unsigned int)time(nullptr));
    pthread_mutex_t mtx;
    pthread_mutex_init(&mtx, nullptr);

    pthread_t tid[Thread_NUM];
    // 创建多个线程
    for (int i = 0; i < Thread_NUM; i++)
    {
        string name = "thread";
        name += to_string(i);
        ThreadData *td = new ThreadData(name, &mtx);
        // 这里传递参数也可以传递自定义对象
        pthread_create(tid + i, nullptr, getTicket, (void *)td);
    }

    // 回收线程
    for (int i = 0; i < Thread_NUM; i++)
    {
        pthread_join(tid[i], nullptr);
    }

    // 销毁锁
    pthread_mutex_destroy(&mtx);
    return 0;
}


